package com.mvu.banana.common.server;

import javax.servlet.http.HttpServletRequest;

import com.mvu.banana.common.client.PermissionDTO;
import com.mvu.banana.common.client.ServiceToken;
import com.mvu.banana.common.client.SystemConstants;

/**
 * Class description...
 *
 * @author gantz
 */
public class PermissionChecker extends AJAXServlet<PermissionDTO> implements SystemConstants{
  private PermissionChecker(){}
  private static PermissionChecker INSTANCE;
  public static PermissionChecker get(){
    if(INSTANCE == null){
      INSTANCE = new PermissionChecker();
    }
    return INSTANCE;
  }

  public boolean isAuthorized(HttpServletRequest request) {
    String module = (String) request.getAttribute(PAGE_ATTR);
    if (module == GUEST) {
      return true;
    }
    ServiceToken serviceToken = SessionManager.get().getServiceToken(request);
    String username = serviceToken.getUsername();
    String authKey = request.getParameter(AUTH_KEY_PARAM);
    return isAuthorized(module, username, authKey);
  }

  private boolean isAuthorized(String module, String userID, String authKey) {
    // TODO make this public key
    if(SECRET_CODE.equals(authKey)){
      return true;
    }
    if (userID == null) {
      return false;
    }
    // TODO authenticate
    return true;
  }

  @Override
  public PermissionDTO post(PermissionDTO dto) {
    ServiceToken serviceToken = SessionManager.get().getServiceToken(request);
    // TODO permission
    dto.username = serviceToken.getUsername();
    if(SECRET_CODE.equals(dto.authKey)){
      dto.authKeyAccepted = true;
    }
    return dto;
  }
}
